import React, { useMemo, useState } from 'react'
import { Button } from 'antd-mobile'

export default function CalendarView({ weights }) {
  const [currentDate, setCurrentDate] = useState(new Date())
  const currentMonth = currentDate.getMonth()
  const currentYear = currentDate.getFullYear()

  const monthDays = useMemo(() => {
    const firstDay = new Date(currentYear, currentMonth, 1).getDay()
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate()
    const daysInPrevMonth = new Date(currentYear, currentMonth, 0).getDate()
    const days = []
    for (let i = firstDay - 1; i >= 0; i--) days.push(new Date(currentYear, currentMonth - 1, daysInPrevMonth - i))
    for (let i = 1; i <= daysInMonth; i++) days.push(new Date(currentYear, currentMonth, i))
    const remainingDays = 42 - days.length
    for (let i = 1; i <= remainingDays; i++) days.push(new Date(currentYear, currentMonth + 1, i))
    return days
  }, [currentMonth, currentYear])

  const weightMap = useMemo(() => {
    const map = {}
    weights.forEach(w => { map[w.date] = w.weight })
    return map
  }, [weights])

  const formatDate = (d) => d.toISOString().split('T')[0]
  const getWeightForDate = (d) => weightMap[formatDate(d)] || null

  const monthName = new Intl.DateTimeFormat('zh-CN', { month: 'long' }).format(new Date(currentYear, currentMonth))

  const handlePrevMonth = () => setCurrentDate(new Date(currentYear, currentMonth - 1, 1))
  const handleNextMonth = () => setCurrentDate(new Date(currentYear, currentMonth + 1, 1))

  const today = new Date(); today.setHours(0,0,0,0)
  const formatToday = formatDate(today)

  return (
    <div style={{background:'#fff', padding:12, borderRadius:8}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
        <h3>{currentYear} 年 {monthName}</h3>
        <div>
          <Button size='small' onClick={handlePrevMonth}>上月</Button>
          <Button size='small' onClick={handleNextMonth} style={{marginLeft:8}}>下月</Button>
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:6}}>
        {['日','一','二','三','四','五','六'].map(d=>(<div key={d} style={{textAlign:'center', fontWeight:600}}>{d}</div>))}
        {monthDays.map((day, idx)=>{
          const dateStr = formatDate(day)
          const weight = getWeightForDate(day)
          const isCurrentMonth = day.getMonth() === currentMonth
          const isToday = dateStr === formatToday
          const bg = !isCurrentMonth ? '#fafafa' : isToday ? '#3b82f6' : weight ? '#e6fffa' : 'transparent'
          const color = isToday ? '#fff' : '#111'
          return (
            <div key={idx} style={{minHeight:64, padding:6, borderRadius:6, background:bg, color}}>
              <div style={{fontSize:12}}>{day.getDate()}</div>
              {weight != null && <div style={{marginTop:6, fontWeight:700}}>{weight.toFixed(1)}</div>}
            </div>
          )
        })}
      </div>
    </div>
  )
}
